﻿
#include "Network/TCPClient.h"
#include "Async/PackagedTask.h"

#include "Platform/Socket/SocketPlatform.h"

CTCPClient::CTCPClient()
{
    PlatformData=new CSocketPlatformData();
}

CTCPClient::~CTCPClient()
{
    Disconnect();

    delete PlatformData;
}

TThreadSafeSharedPtr<CTCPClient> CTCPClient::Create()
{
    TThreadSafeSharedPtr<CTCPClient> Client=new CTCPClient();
    return Client;
}



bool CTCPClient::IsConnected()
{
    return State==ETCPClientState::Connected;
}

TVector<uint8_t> CTCPClient::ReadAllData()
{
    std::lock_guard<std::mutex> Lock(ReceivedDataMutex);
    return std::move(ReceivedData);
}

void CTCPClient::Send(const TVector<uint8_t> &InMessage)
{
    std::lock_guard<std::mutex> Lock(SendDataMutex);
    SendData.Append(InMessage);
}

void CTCPClient::Send(const CString &InMessage)
{
    Send(InMessage.ToUtf8String());
}

void CTCPClient::Send(const CString8 &InMessage)
{
    TVector<char8_t> Data=InMessage.GetData();
    TVector<uint8_t> SizeData((uint8_t*)Data.Data(),Data.Num() -1 /*remove \0 */  );
    Send(SizeData);
}

void CTCPClient::PostConnected()
{
    StartReceiveAndDetectTask();
    StartSendTask();
}

